package oicon;

import java.awt.Color;
import java.awt.Cursor;
import java.awt.Desktop;
import java.awt.Graphics;
import java.awt.Insets;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.net.URI;

import javax.swing.JLabel;

/**HyperLinkLabel
 * */
@SuppressWarnings("serial")
public class HyperLinkLabel extends JLabel {
	
	
	private Color underlineColor = Color.BLUE;
	private URI uriTarget;
	
	/**HyperLinkLabel
	 * @param label - label string
	 * @param uri - URI for open
	 * */
	public HyperLinkLabel(String label, final URI uri) {
		super(label);
		uriTarget = uri;
		setForeground(Color.BLUE.brighter());
		setCursor(new Cursor(Cursor.HAND_CURSOR));
		addMouseListener(new customMouseAdapter());
	}

	@Override
	protected void paintComponent(Graphics g) {
		super.paintComponent(g);

		g.setColor(underlineColor == null ? getForeground() : underlineColor);

		Insets insets = getInsets();

		int left = insets.left;
		if (getIcon() != null)
			left += getIcon().getIconWidth() + getIconTextGap();

		g.drawLine(left, getHeight() - 1 - insets.bottom,
				(int) getPreferredSize().getWidth() - insets.right,
						getHeight()- 1 - insets.bottom);
	}

	/**MouseAdaper
	 * */
	private class customMouseAdapter extends MouseAdapter {
		@Override
		public void mouseClicked(MouseEvent e) {
			open(uriTarget);
		}
		@Override
		public void mouseEntered(MouseEvent e) {
			setForeground(Color.ORANGE);
			underlineColor = Color.ORANGE;
		}
		@Override
		public void mouseExited(MouseEvent e) {
			setForeground(Color.BLUE.brighter());
			underlineColor = null;
		}
	}

	/**Open uri in default browser
	 * @param uri - uri target
	 * */
	private void open(URI uri) {
		if (Desktop.isDesktopSupported()) {
			Desktop desktop = Desktop.getDesktop();
			try {
				desktop.browse(uri);
			} catch (IOException e) {;}
		}
	}
}
